package goldeneagle.com.user.servlet;

import com.alibaba.fastjson.JSONObject;
import goldeneagle.com.entity.User;

import goldeneagle.com.user.service.UserService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

import java.util.*;

/*
 *Created by GHW
 *Description:修改个人信息
 *2019/11/13 10:26
 */
@WebServlet(value = "/UpdateUserInfoServlet")
public class UpdateUserInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        response.addHeader("Access-Control-Allow-Origin", "*");
//        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
//        response.addHeader("Access-Control-Allow-Headers","x-requested-with,content-type");
//        response.addHeader("content-type","application:json;charset=utf8");
        User user = new User();
        UserService userService = new UserService();
//        -------------文件上传-----------------
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        // 判断表单中是否存在multipart属性
        String fileName;
        if (isMultiPart) {
            try {
                // 创建工厂类
                DiskFileItemFactory factory = new DiskFileItemFactory();
                // 创建解析器
                ServletFileUpload upload = new ServletFileUpload(factory);
                // 使用解析器解析form表单中的请求字段，并保存到items集合中
                List items = upload.parseRequest(request);
                Iterator<FileItem> iterator = items.iterator();
                HashMap<String, String> propertyMap = new HashMap<>();
                while (iterator.hasNext()) {
                    FileItem item = iterator.next();
                    // 获取请求名称
                    String itemName = item.getFieldName();
                    // 判断请求字段是普通文本项<true>还是文件项<false>
                    if (item.isFormField()) {
                        propertyMap.put(itemName, item.getString("UTF-8"));
                    } else {
                        fileName = item.getName();
                        // 获取服务器端实际路径
                        if (!fileName.equals("")) {
                            String path = request.getSession().getServletContext().getRealPath("upload");
                            System.out.println("服务器端实际路径：" + path);
                            File file = new File(path, fileName);
                            File mkdir = new File(path);
                            mkdir.mkdir();
                            item.write(file);
                            propertyMap.put(itemName, fileName);
                        }
                        propertyMap.put(itemName, fileName);
                    }
                }
                //如果img（头像）为空，那么使用原来的img
                //如果密码为空，那么就用原来的密码

                if (propertyMap.get("img") == null || propertyMap.get("img").equals("")) {
                    if (propertyMap.get("newPassword") == null || propertyMap.get("confirmNewPassword") == null || propertyMap.get("newPassword").equals("") || propertyMap.get("confirmNewPassword").equals("")) {
                        user = new User(Integer.parseInt(propertyMap.get("id")), propertyMap.get("username"), propertyMap.get("password"),
                                propertyMap.get("address"), propertyMap.get("email"), propertyMap.get("imgName"),
                                propertyMap.get("userType"));
                    }
                    //传入user，执行修改方法
                    request.setAttribute("currentUser", user);
                    userService.UpdateUserInfo(user);
                    //成功返回ok
                    response.getWriter().write("ok");
                    System.out.println("{ok:" + user.toString() + "}");
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                } else {
                    //如果修改了img，那么使用新的img
                    //如果密码不为空，那么使用新密码
                    if (propertyMap.get("newPassword") != null || propertyMap.get("confirmNewPassword") != null || !propertyMap.get("newPassword").equals("") || !propertyMap.get("confirmNewPassword").equals("")) {
                        user = new User(Integer.parseInt(propertyMap.get("id")), propertyMap.get("username"), propertyMap.get("confirmNewPassword"),
                                propertyMap.get("address"), propertyMap.get("email"), propertyMap.get("img"),
                                propertyMap.get("userType"));
                        //传入user，执行修改方法
                        request.setAttribute("currentUser", user);
                        userService.UpdateUserInfo(user);
                        //成功返回ok
                        response.getWriter().write("ok");
                        System.out.println("{ok:UpdateUserInfo" + user.toString() + "}");
                        request.getRequestDispatcher("index.jsp").forward(request, response);
                    } else {
                        System.out.println("出问题了");
                    }
                }
            } catch (FileUploadBase.SizeLimitExceededException e) {
                response.getWriter().write("failed:文件过大，请修改");
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                response.getWriter().write("failed:系统错误");
            }
//        --------------文件上传END----------------
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
